import 'package:amap_core_fluttify/amap_core_fluttify.dart';
import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import 'package:flutter/cupertino.dart';
import 'package:zpub_third/zpub_third.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:zpub_track/com/zerogis/zpubtrack/constant/GDMapConstant.dart';
import 'package:zpub_track/com/zerogis/zpubtrack/constant/KeyConstant.dart';
/*
 * 类描述：高精度定位(新版高德定位SDK)
 * 坐标收集器：只负责收集坐标，考虑到坐标可能本地化此类只负责收集，将坐标本地化或者网络化需要配合其他类进行使用(CollectManager)
 * 作者：郑朝军 on 2019/5/10
 * 邮箱：1250393285@qq.com
 * 公司：武汉智博创享科技有限公司
 * 修改人：郑朝军 on 2019/5/10
 * 修改备注：
 */
class LocationManager
{
  static LocationManager mInstance;

  // 收集的坐标点
  List mCoors = [];

  // 最后收集的坐标点
  String mLastCoor;

  static LocationManager getInstance()
  {
    if (mInstance == null)
    {
      mInstance = new LocationManager();
    }
    return mInstance;
  }

  LocationManager()
  {
    PermissionUtil.initPermission([
      PermissionGroup.location,
    ]);
    AmapCore.init(KeyConstant.APP_KEY_GD);
  }

  /*
   * 直接获取到定位，不必先启用监听
   */
  Future<Location> getLocation()
  {
   return AmapLocation.fetchLocation().then((location){
      setDefaultLocation(location);
      return location;
    });
  }

  /*
   * 启动位置时时改变监听
   */
  void startListenLocation({ValueChanged<dynamic> valueChanged, bool isPush:false}) async
  {
    await for (final location in AmapLocation.listenLocation())
    {
      // 回调
      if(valueChanged != null)
      {
        valueChanged(location);
      }

      // 入栈
      if(isPush)
      {
        pushCoors(location);
      }
    }
  }

  /*
   * 设置默认位置的相关值
   */
  void setDefaultLocation(Location location)
  {
    location.province.then((value) =>  GDMapConstant.PROVINCE = value);
    location.city.then((value) =>  GDMapConstant.CITY = value);
    location.district.then((value) =>  GDMapConstant.AREA = value);
    location.address.then((value) =>  GDMapConstant.ADDRESS = value);
    location.latLng.then((value) {
      GDMapConstant.LATITUDE = value.latitude;
      GDMapConstant.LONGITUDE = value.longitude;
    });
  }

  /*
   * 启动监听位置改变
   */
  void startLocation()
  {
  }

  /*
   * 关闭定位
   */
  void stopLocation()
  {
    destroyLocation();
  }

  /*
   * 关闭定位
   */
  void destroyLocation()
  {
    AmapLocation.stopLocation();
  }

  /*
   * 将收集到最新的坐标入栈
   * @param {Object} location 返回的对象
   */
  void pushCoors(location)
  {
    location.latLng.then((value)
    {
      String coor = value.longitude.toString() + ',' + value.latitude.toString() + ';';
      if (isLinkCoor(this.mLastCoor, coor))
      {
        this.mLastCoor = coor;
        mCoors.add(value);
      }
    });
  }

  /*
   * 判断是否需要连接坐标
   *
   * @param lastCoor 最后一个位置
   * @param coor     最新获取到的点
   * @return 【true = 需要连接坐标串】
   */
  bool isLinkCoor(lastCoor, coor)
  {
    if (lastCoor != coor)
    {
      return true;
    }
    else
    {
      return false;
    }
  }
}
